-- 对比语言,生成增量文件,并保存

-- 比较文件
function CompareFile(pathA, pathB)
	local data = {}
	local oldLanguage = dofile(pathA)
	local newLanguage = dofile(pathB)
	
	for key, value in pairs(newLanguage) do
		if oldLanguage[key] ~= newLanguage[key] then
			data[key] = value
		end
	end

	return data
end

-- 系列化
function Serialize(data)
	local str = ""
	str = str .. "-- 语言增量文件,自动生成,请勿修改!!!\n\n"
	str = str .. "local data = {\n"
	for k,v in pairs(data) do
		str = str .. string.format("    [\"%s\"] = \"%s\",\n", k, string.gsub(v, "\n", "\\n"))
	end

	str = str .. "}\n\n"
	str = str .. "return data"

	return str
end

-- 保存到文件
function SaveToFile(path, content)
	local file = assert(io.open(path, "w+"))
	file:write(content)
	file:flush()
	file:close()
end

function GetFileName(filename)
	return string.match(filename, ".+/([^/]*%.%w+)$")
end

function main()
	if #arg < 2 then
		print("参数错误")
		return
	end

	local filePathA = arg[1]
	local filePathB = arg[2]
	local pathDst = arg[3]

	local fileNameA = GetFileName(filePathA)
	local fileNameB = GetFileName(filePathB)

	if fileNameA ~= fileNameB then
		print(string.format("参数错误,文件名不匹配: %s - %s", fileNameA, fileNameB))
		return
	end

	local filePathDst = string.format("%s/%s.lua", pathDst, string.sub(fileNameA, 1, -5))

	local data = CompareFile(filePathA, filePathB)
	local text = Serialize(data)

	SaveToFile(filePathDst, text)
end

main()